package com.logistic.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.logistic.dao.HibernateSessionFactory;
import com.logistic.dao.UserDao;
import com.logistic.domain.Article;
import com.logistic.domain.ConsumeRecord;
import com.logistic.domain.User;
import com.logistic.page.QueryResult;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
	private Log log = LogFactory.getFactory().getLog(getClass());
	
	@SuppressWarnings("rawtypes")
	public List getAll() {
		List list = null;
		try
		{
		Session s = HibernateSessionFactory.getSession();
		String hql = "from User user order by user.Uid asc";
		list = s.createQuery(hql).list();
		if (list.isEmpty()) {
			return null;
		}
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		//return getHibernateTemplate().find("from User user order by user.Uid asc");
		
		return list;
	}
	
	public User login(User user) {
		User newUser = null;
		try{
			Session s = HibernateSessionFactory.getSession();
			String hql = "from User user where user.Uemail ='" + user.getUemail().trim() + "' and user.Upassword='" + user.getUpassword().trim() + "'";
			Query q = s.createQuery(hql);
			List list = q.list();
			if(list.isEmpty() || list.size()==0) {
				return null;
			}
			newUser = (User)list.get(0);
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		
//		List list = getHibernateTemplate().find("from User user where user.Uemail =? and user.Upassword=?", 
//				user.getUemail().trim(), user.getUpassword().trim());
//		if(list.isEmpty() || list.size()==0) {
//			return null;
//		}
//		newUser = (User)list.get(0);
		
		return newUser;
	}
	
	@SuppressWarnings("finally")
	public int save(User user) {
		Session s = HibernateSessionFactory.getSession();
		Transaction t = s.beginTransaction();
		
		s.saveOrUpdate(user);
		try {
			t.commit();
		} catch (Exception e) {
			
		} finally {
			HibernateSessionFactory.closeSession();
			return 1;
		}
		
//		getHibernateTemplate().save(user);
//		return 1;
	}
	
//	public int modify(User user) {
//		try{
//			Session s = HibernateSessionFactory.getSession();
//			Transaction t = s.beginTransaction();
//			Query q = s.createQuery("update User user set user.Uemail=?, " 
//					+ "user.Uname=?, user.Utelephone=?, user.UcontactAdress=?, user.Uzip=?,user.UwangwangNum=?, "
//					+ "user.UQQNum=?, user.UmsnNum=?, user.Unote=?"
//					+ " where user.Uid=?");
//			q.setParameter(0, user.getUemail());
//			q.setParameter(1, user.getUname());
//			q.setParameter(2, user.getUtelephone());
//			q.setParameter(3, user.getUcontactAdress());
//			q.setParameter(4, user.getUzip());
//			q.setParameter(5, user.getUwangwangNum());
//			q.setParameter(6, user.getUQQNum());
//			q.setParameter(7, user.getUmsnNum()); 
//			q.setParameter(8, user.getUnote());
//			q.setParameter(9, user.getUid());
//			q.executeUpdate();
//			t.commit();
//		}catch(HibernateException e){
//			e.printStackTrace();
//		}finally
//		{
//			HibernateSessionFactory.closeSession();
//			return 1;
//		}
//	
//	}
	public int modify(User user) {
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			String sql = "update User user set ";
			if( user.getUemail() != null && !"".equals(user.getUemail())){
				sql = sql + "user.Uemail='"+user.getUemail()+"', ";
			}
			if( user.getUname() != null && !"".equals(user.getUname())){
				sql = sql + "user.Uname='"+user.getUname()+"', ";
			}
			if( user.getUtelephone() != null && !"".equals(user.getUtelephone())){
				sql = sql + "user.Utelephone='"+user.getUtelephone()+"', ";
			}
			if( user.getUcontactAdress() != null && !"".equals(user.getUcontactAdress())){
				sql = sql + "user.UcontactAdress='"+user.getUcontactAdress()+"', ";
			}
			
			if( user.getUzip() != null && !"".equals(user.getUzip())){
				sql = sql + "user.Uzip='"+user.getUzip()+"', ";
			}
			if( user.getUwangwangNum() != null && !"".equals(user.getUwangwangNum())){
				sql = sql + "user.UwangwangNum='"+user.getUwangwangNum()+"', ";
			}
			if( user.getUQQNum() != null && !"".equals(user.getUQQNum())){
				sql = sql + "user.UQQNum='"+user.getUQQNum()+"', ";
			}
			if( user.getUmsnNum() != null && !"".equals(user.getUmsnNum())){
				sql = sql + "user.UmsnNum='"+user.getUmsnNum()+"', ";
			}
			if( user.getUnote() != null && !"".equals(user.getUnote())){
				sql = sql + "user.Unote='"+user.getUnote()+"', ";
			}
			if( user.getUrecommendId() != null && !"".equals(user.getUrecommendId())){
				sql = sql + "user.UrecommendId='"+user.getUrecommendId()+"', ";
			}
			if( user.getUrecommendBonusFlag() != null && !"".equals(user.getUrecommendBonusFlag())){
				sql = sql + "user.UrecommendBonusFlag='"+user.getUrecommendBonusFlag()+"', ";
			}
		
			
			sql = (String)sql.subSequence(0, sql.length()-2);
			Query q = s.createQuery(sql
					+ " where user.Uid=?"); 
			q.setParameter(0, user.getUid());
			q.executeUpdate();
			t.commit();

		}catch(HibernateException e){
			e.printStackTrace();
		}finally
		{
			HibernateSessionFactory.closeSession();	
		}
		return 1;
	}
	
	public void delete(String id) {
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction tran = s.beginTransaction();
			Query q = s.createQuery("delete from Record where id=?");
			q.setParameter(0, id);
			q.executeUpdate();
			tran.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
	
	public boolean checkEmailExist(String email){
		List list = new ArrayList();
		try{
			Session s = HibernateSessionFactory.getSession();
			String hql = "from User user where user.Uemail =?";
			Query q = s.createQuery(hql);
			q.setParameter(0, email.trim());
			list = q.list();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		if( list.isEmpty() || list.size()==0) {
			log.info("parameter email is "+ email.trim()+" ,this email is not exist");
			return false;
		}else{
			return true;	
		}
		
	}
 
	public boolean checkUidExist(String uId){
		List list = null;
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			
			String hql = "from User user where user.Uid =?";
			Query q = s.createQuery(hql);
			q.setParameter(0, uId);
			list = q.list();
			t.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		if(list.isEmpty() || list.size()==0) {
			return false;
		}else{
			return true;	
		}
	}
	
	public boolean checkUreceveIdExist(String uId){
		List list = null;
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			
			String hql = "from User user where user.UreceiveId =?";
			Query q = s.createQuery(hql);
			q.setParameter(0, uId);
			list = q.list();
			t.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		if(list.isEmpty() || list.size()==0) {
			return false;
		}else{
			return true;	
		}
	}
	
	
	public User getUserByUid(User user){
		User newUser = null;
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			String hql = "from User user where user.Uid =?";
			Query q = s.createQuery(hql);
			q.setParameter(0, user.getUid());
			List list = q.list();
			t.commit();
			if(list.isEmpty() || list.size()==0) {
				return null;
			}
			newUser = (User)list.get(0);
		}catch(HibernateException e){
			e.printStackTrace();
		}finally
		{
			HibernateSessionFactory.closeSession();
		}
		return newUser;
	}
	
	public User getUserByUreceiveId(User user){
		User newUser = null;
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			String hql = "from User user where user.UreceiveId =?";
			Query q = s.createQuery(hql);
			q.setParameter(0, user.getUreceiveId());
			List list = q.list();
			t.commit();
			if(list.isEmpty() || list.size()==0) {
				return null;
			}
			newUser = (User)list.get(0);
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		return newUser;
	}
	
	public void changePassword(User user,String pass){
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			Query q = s.createQuery("update User user set user.Upassword=? " 
					+ " where user.Uid=?");
			q.setParameter(0, pass);
			q.setParameter(1, user.getUid());
			
			q.executeUpdate();
//			s.saveOrUpdate(record);
			t.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally
		{
			HibernateSessionFactory.closeSession();
		}
	}
	
	public int createChargeRecord(ConsumeRecord record) {
		Session s = HibernateSessionFactory.getSession();
		Transaction t = s.beginTransaction();
		s.save(record);
		try {
			t.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			HibernateSessionFactory.closeSession();
			return 1;
		}
		
		
	}
	
	public ConsumeRecord getChargeRecord(String id) {
		ConsumeRecord record = null;
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			String hql = "from ConsumeRecord where id =?";
			Query q = s.createQuery(hql);
			q.setParameter(0, id);
			List list = q.list();
			t.commit();
			if(list.isEmpty() || list.size()==0) {
				return null;
			}
			record = (ConsumeRecord)list.get(0);
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		return record;
	}
	
	public void updateChargeRecord(String id, String flag) {
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			Query q = s.createQuery("update ConsumeRecord set successFlag=? " 
					+ " where id=?");
			q.setParameter(0, flag);
			q.setParameter(1, id);
			q.executeUpdate();
			t.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
	
	public QueryResult showConsumptionHistory(String Uid,int first,int max, String action) {
		QueryResult qr = new QueryResult();
		try{
			Session s = HibernateSessionFactory.getSession();
			String hql = "from ConsumeRecord where uId=? and successFlag != ? ";
			
			if(action!=null && !"".equals(action)) {
				hql += " and accountAction=?";
			}
			hql += " order by operationTime desc";
			Query q = s.createQuery(hql);
			q.setFirstResult(first);
			q.setMaxResults(max);
			q.setParameter(0, Uid);
			q.setParameter(1, "N");
			
			if(action!=null && !"".equals(action)) {
				q.setParameter(2, action);
			}
			List list = q.list();
			Query size = s.createQuery(hql);
			size.setParameter(0, Uid);
			size.setParameter(1, "N");
			if(action!=null && !"".equals(action)) {
				size.setParameter(2, action);
			}
			qr.setTotalrecord(size.list().size());
			
			qr.setResultlist(list);
		}catch(HibernateException e){
			e.printStackTrace();
		}finally
		{
			HibernateSessionFactory.closeSession();
		}
		return qr;
	}
	
	public void createArticle(Article article) {
		try{
			Session s = HibernateSessionFactory.getSession();
			Transaction t = s.beginTransaction();
			s.save(article);
			t.commit();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
	
	public List getArticle(String type, int count) {
		List list = null;
		try{
			Session s = HibernateSessionFactory.getSession();
			String hql = "from Article where type=? and active='Y' order by updatedDt Desc";
			Query q = s.createQuery(hql);
			q.setParameter(0, type);
			if(count > 0) {
				q.setMaxResults(count);	
			}
			list = q.list();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		return list;
	}
}
